<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Article extends Controller
{
    public function index()
    {
        $keywords = input('keywords');
        $cateId = input('cate_id');
        $list = db('article')->where('status','>=',0)->where('title','LIKE',"%{$keywords}%");
        if($cateId)
        {
            $list = $list->where('cate_id',$cateId);
        }
        $list = $list->order('is_top DESC,sort DESC,id DESC')->paginate(10,false,['query'=>$this->request->param()]);
        $this->assign([
            'list'=>$list,
            'cateList'=>$this->getCateList(),
        ]);
        return view();
    }
    
    public function edit()
    {
		$id = input()['id'];
        $adminId = session('uid','','admin');
        if(request()->isAjax()){
            $data=input('post.')['data'];
            $data['admin_id'] = session('uid','','admin');
            $data['attachments'] = json_encode($data['attachments']);
            if(!$data['id'])
            {
                $data['add_time'] = time();
                $save = db('article')->insert($data);
            }
            else
            {
                db('article')->where('id',$data['id'])->update($data);
                $save = 1;
            }
            if($save ){
                return ['msg'=>'提交成功','icon'=>1];
            }else{
                return ['msg'=>'提交失败','icon'=>2];
            }
            return;
        }
        if($id)
        {
            $data = db('article')->where('id',$id)->find();
        }
    	$this->assign([
    		'data'=>$data,
            'cateList'=>$this->getCateList(),
    	]);
        return view();
    }
    
    public function view()
    {
        $id = input()['id'];
        $data = db('article')->where('id',$id)->find();
    	$this->assign([
    		'data'=>$data,
    	]);
        return view();
    }
    
    public function del()
    {
        $id = input()['id'];
        $adminId = session('uid','','admin');
        if($id)
        {
            db('article')->where('id',$id)->update(['status'=>-1]);
            return ['msg'=>'提交成功','icon'=>1];
        }
    }
    
    public function cateList()
    {
        
    }
    
    public function cateEdit()
    {
        
    }
    
    private function getCateList()
    {
        return db('article_cate')->where('status','>=',0)->order('id ASC')->select();
    }
    
}